<template>
  <div class="body">
    <el-button ref="busdata" :isedit="false" @click="drawer = true" type="primary" plain>{{
        $route.meta.name
      }}
    </el-button>
    <el-drawer
        title="文章信息"
        :visible.sync="drawer"
        direction="rtl"
        :before-close="handleClose">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="文章标题" name="1">
          <el-input
              placeholder="请输入文章标题"
              v-model="Article_obj.title"
              clearable>
          </el-input>
        </el-collapse-item>
        <el-collapse-item title="文章标签和分类" name="2">
          <el-select
              v-model="Article_obj.tag"
              multiple
              filterable
              allow-create
              collapse-tags
              placeholder="请输入文章标签">
            <el-option v-for="(item,index) in ArticleInfo.tags" :key="item.id" :label="item.title"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-select
              v-model="Article_obj.category"
              collapse-tags
              clearable
              style="margin-left: 20px;"
              placeholder="请输入文章分类">
            <el-option v-for="(item,index) in ArticleInfo.category" :key="item.id"
                       :label="item.title"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-collapse-item>
        <el-collapse-item title="文章摘要" name="3">
          <el-input
              type="textarea"
              :rows="5"
              placeholder="摘要：会在推荐、列表等场景外露，帮助读者快速了解内容,如果不填则默认为正文的前256个字"
              resize="none"
              maxlength="256"
              show-word-limit
              v-model="Article_obj.abstract">
          </el-input>
        </el-collapse-item>
        <el-collapse-item title="文章封面" name="4">
          <el-upload
              ref="upload"
              action="/api/addcover/"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :limit="1"
              :on-exceed="Exceedlimit"
              :file-list="Article_obj.fileList"
              :auto-upload="false"
              :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="imageUrl" alt="">
          </el-dialog>
          <el-button
              size="mini"
              round
              class="getcover"
              @click="getcover"
          >获取随机背景
          </el-button>
        </el-collapse-item>
        <el-button class="draft" @click="addSaveDetails" round>保存草稿</el-button>
        <el-button class="release" @click="addReleaseDetails" type="danger" round>发布文章</el-button>
      </el-collapse>
    </el-drawer>
    <Markdown></Markdown>
  </div>
</template>

<script>
import {mapState, mapActions, mapMutations} from 'vuex'
import Markdown from '@/components/MarkDown'

export default {
  name: "AddArticle",
  components: {
    Markdown
  },
  data() {
    return {
      // 是否显示完善文章信息框
      drawer: false,
      // 表示当前完善文章信息框正在显示的窗口
      activeName: '1',
      imageUrl: '',
      dialogVisible: false
    }
  },
  methods: {
    ...mapActions('Article', ['addArticle', 'getArticleInfo', 'getArticlecontent']),
    ...mapMutations('Article', ['cleanArticle_obj', 'setArticle_obj']),
    // 弹出框关闭按钮
    handleClose() {
      this.drawer = false
    },
    // 保存文章详情
    addSaveDetails() {
      let Article_obj = this.Article_obj
      Article_obj.status = 0
      Article_obj.id = this.ArticleNid  // 发送此时处理的文章id
      // 上传文章封面
      if (this.Article_obj.cover === -1) {
        this.$refs.upload.submit()
      }
      this.addArticle(Article_obj).then(value => {
        if (value['code'] === 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.drawer = false
        } else {
          this.$message({
            message: value['info'],
            type: 'error'
          })
        }
      })
    },
    // 发布文章详情
    addReleaseDetails() {
      let Article_obj = this.Article_obj
      Article_obj.status = 1
      Article_obj.id = this.ArticleNid  // 发送此时处理的文章id
      // 上传文章封面
      if (this.Article_obj.cover === -1) {
        this.$refs.upload.submit()
      }
      // 发布文章请求
      this.addArticle(Article_obj).then(value => {
        if (value['code'] === 200) {
          this.$message({
            message: value['info'],
            type: 'success'
          })
          setTimeout(() => {
            this.$router.push({
              name: "article",
              params: {
                id: this.ArticleNid
              }
            })
          }, 50)
          this.cleanArticle_obj()
        } else {
          console.log('错误', value['value']['info'], typeof value)
          this.$message({
            message: value['value']['info'],
            type: 'error'
          })

        }
      })
    },
    // 设置随机封面
    getcover() {
      this.fileList = [this.ArticleInfo.cover[Math.floor(Math.random() * 3)],]
      this.Article_obj.cover = this.fileList[0]['id']
    },
    // 上传前的回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是JPG格式或者PNG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG || isPNG && isLt2M;
    },
    // 上传文件超过数量回调
    Exceedlimit() {
      this.$message.error('文件数量超过限制!');
    },
    // 删除封面时的回调
    handleRemove(file, fileList) {
      this.imageUrl = ''
    },
    // 上传成功的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 点击文件列表中已上传的文件时的回调
    handlePictureCardPreview(file) {
      this.imageUrl = file.url;
      this.dialogVisible = true;
    },
  },
  computed: {
    ...mapState('Article', ['Article_obj', 'ArticleInfo', 'ArticleNid', 'Articlecontent'])
  },
  mounted() {
    this.getArticleInfo()
    // 如果是编辑页面，则获取文章详细信息
    if (this.$route.name === 'EditArticle') {
      this.getArticlecontent(this.$route.params.id).then(value => {
        this.setArticle_obj(this.Articlecontent)
      })
    }
  },
  beforeDestroy() {
    this.cleanArticle_obj()
  }
}
</script>

<style lang="less">
.body {
  height: 100%;
}

// 完善信息栏
.el-drawer__body {
  position: relative;

  .el-collapse {
    padding: 0 20px;

    > .el-collapse-item:nth-child(2) {

      .el-collapse-item__content {
        display: flex;
        // 删除上传组件的动画
        .el-upload-list__item {
          transition: none;
        }

        .el-select:nth-child(1) {
          margin-left: 0;
        }
      }
    }

    > .el-collapse-item:nth-child(3) {
      position: relative;
    }

    > .el-collapse-item:nth-child(4) {
      .el-collapse-item__content {
        display: flex;
        justify-content: center;
        position: relative;
        // 获取随机封面按钮
        .getcover {
          position: absolute;
          right: 10px;
          bottom: 5px;
        }
      }
    }

    // 保存草稿按钮
    .draft {
      position: absolute;
      right: 144px;
      bottom: 20px;
    }

    // 发布按钮
    .release {
      position: absolute;
      right: 20px;
      bottom: 20px;
    }
  }
}
</style>